package com.robusta.app.page;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

public class LoginPageFixture {
    private final String appURL = "http://localhost:7890/web/home.html";
    private WebDriver driver;
    private WebElement userName;
    private WebElement password;
    private WebElement loginButton;

    private LoginPageFixture(){
        driver = new HtmlUnitDriver(true);
        driver.get(appURL);
        userName = driver.findElement(By.id("userName"));
        password = driver.findElement(By.id("password"));
        loginButton = driver.findElement(By.id("login"));
    }

    public static LoginPageFixture aLoginPage() {
        return new LoginPageFixture();
    }

    public LoginPageFixture waitTillPageIsDisplayed() {
        (new WebDriverWait(driver, 60)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.getTitle().toLowerCase().startsWith("login");
            }
        });
        return this;
    }

    public LoginPageFixture withCredentials(String user, String password) {
        this.userName.sendKeys(user);
        this.password.sendKeys(password);
        return this;
    }

    public LoginPageFixture login() {
        this.loginButton.click();
        return this;
    }

    public LoginPageFixture assertLoginReDisplayed() {
        assertThat(driver.getTitle().toLowerCase(), startsWith("login"));
        return this;
    }

    public LoginPageFixture assertLoginFailedMessageIsDisplayed() {
        WebElement errors = driver.findElement(By.id("errors"));
        assertNotNull(errors);
        assertThat(errors.getText(), is(equalTo("Login failed. Please try again...")));
        return this;
    }
}
